/**
 * 
 */
define([], function() {
	var FileUploader=function(params){
		params = $.extend({
            auto: true,
            swf: root + '/res/jsLib/component/webuploader/Uploader.swf',
            server: ctx + '/attachmentAction/upload.do',
            uploadPick: '#uploadPick',
            uploadList: "#uploadList",
            resize: false,
            storageType: 2,
            isSingle:false,
            duplicate:undefined, 
            storageAddress: "/upload",
            fileVal: 'filedata',
            accept: {
                title: '通用文件类型',
                //需要与platform.upload.allowFileTypes配置保持一致
                extensions: 'doc,docx,xls,xlsx,ppt,pptx,wps,viso,pdf,txt,jpg,gif,png,bmp,swf,fla,zip,rar'
            }
        }, params);

        var setting = {
            auto: params.auto,
            swf: params.swf,
            server: params.server,
            pick: params.uploadPick,
            resize: params.resize,
            duplicate:params.duplicate,
            formData: {storageType: params.storageType, storageAddress: params.storageAddress},
            fileVal: 'filedata',
            fileNumLimit:params.isSingle?1:undefined,
            accept: params.accept
        };
        var isSetList=false;
        if(params.uploadList){
            var $list = $(params.uploadList);
            isSetList = $(params.uploadList).length>0;
        }
        var state = 'pending';

        var uploader = WebUploader.create(setting);
        uploader.on('beforeFileQueued', function (file) {
        	var checkedSingle=false;
        	if(params.isSingle){
                if($list.find(".item").size()>0){
                	alert("只允许上传一份附件，请删除后重试");
                }else{
                	checkedSingle=true;
                }
            }else{
            	checkedSingle=true;
            }
        	return checkedSingle;
        });
        
        

        // 当有文件被添加进队列的时候
        uploader.on('fileQueued', function (file) {
        	if(isSetList){
                $list.append('<div id="' + file.id + '" class="item am-margin-top-sm">' +
                        '<span class="itemName"><i class="glyphicon glyphicon-paperclip"/>&nbsp;' + file.name +'</span>'+
                        
                        '<div class="progress">' +
                        '<div class="progress-bar"  role="progressbar" aria-valuemin="0" aria-valuemax="100" style="width: 0%">' +
                        '</div>' +
                        '</div>'+
                        '</div>');
        	}
        });
        // 文件上传过程中创建进度条实时显示。
        uploader.on('uploadProgress', function (file, percentage) {
            var $li = $('#' + file.id),
            $percent = $li.find('.progress-bar');

            $percent.css('width', percentage * 100 + '%');
        });
        
        uploader.on('uploadBeforeSend', function (object , data ,headers ) {
        	if(!uploader.attSetId){
        		uploader.attSetId=webUtils.uuid();
        	}
        	data.attSetId=uploader.attSetId;
        	if(params.uploadBeforeSend){
        		params.uploadBeforeSend.call(this,object , data ,headers);
        	}
        });
        
        

        uploader.on('uploadSuccess', function (file, response) {
            if (response) {
                response = eval(response);
                if (response.success) {
                	webUtils.alert("上传成功");
                	if($('#' + file.id).length>0){
                		$('#' + file.id).addClass("text-success");
                        $('#' + file.id).find(".itemName").after('&nbsp;&nbsp;<a href="javascript:void(0)" data-fileid="'+file.id+'" data-attid="'+response.obj.id+'" class="delBtn" ><i class="glyphicon glyphicon-remove"/>删除</a>'+
                        		'&nbsp;&nbsp;<a href="javascript:void(0)"  onclick="webUtils.downloadFile(\''+response.obj.id+'\')"><i class="glyphicon glyphicon-save"/>下载</a>');
                        
                        $('#' + file.id).find(".delBtn").click(function(){
                        	var fileId=$(this).data("fileid");
                        	var attid=$(this).data("attid");
                        	webUtils.delFile(attid,fileId);
                        	uploader.removeFile(fileId,true);
                        });
                	} 
                    
                    		
                } else {
                    $('#' + file.id).addClass("text-warning");
                    webUtils.error("上传出错："+response.msg);
                }
            } else {
                $('#' + file.id).addClass("text-success");
            }
            if(params.onUploadSuccess){
            	params.onUploadSuccess.call(null,file,response,uploader.attSetId);
            }
        });

        uploader.on('uploadError', function (file, reason) {
            $('#' + file.id).addClass("text-warning");
            webUtils.error("上传出错："+reason);
        });

        uploader.on('uploadComplete', function (file) {
            //$('#' + file.id).find('.progress').fadeOut();
        });
        uploader.on('error', function (type) {
            if(type=='Q_EXCEED_NUM_LIMIT'){
            	webUtils.error("超出上传文件最大个数(可以删除文件后再上传)");
            }else if(type=='Q_EXCEED_SIZE_LIMIT '){
            	webUtils.error("超出单个文件上传大小(可以压缩后再上传)");
            }else if(type=='Q_TYPE_DENIED'){
            	webUtils.error("不允许上传该文件类型");
            }else if(type=='F_DUPLICATE'){
            	webUtils.error("请勿重复上传该文件");
            }else{
            	webUtils.error("未知错误："+type);
            }
        });

        if(params.afterInit){
        	params.afterInit.call(this,uploader,this);
        }
	};
	
	return FileUploader;
});
